package horncomb.bpm.hrsm.raw;

import horncomb.bpm.BpmContextHolder;
import horncomb.bpm.process.core.ExecutionContext;
import horncomb.bpm.process.core.NestedToken;
import horncomb.bpm.process.core.StateDefinition;
import horncomb.bpm.process.core.Token;
import horncomb.bpm.process.def.Action;

/**
 * @author Daniel
 */
public class OpenResourceEndAction implements Action {

	/**
	 * {@inheritDoc}
	 */
	public void execute(ExecutionContext context) {
		if (context.getToken() instanceof NestedToken) {
			NestedToken token = ((NestedToken) context.getToken());
			Token parentToken = ((NestedToken) token).getParent();
			if (parentToken != null) {
				int i = BpmContextHolder.getContext()
						.getProcessManagementService().countSubTokenInState(
								token.getParent().getId(),
								new String[] { "verifyEndReject",
										"verifyEndPass" });

				int s = BpmContextHolder.getContext()
						.getProcessManagementService().countSubTokens(
								token.getParent().getId());

				if (s == i) {
					// 所有审批均已经结束
					StateDefinition endState = parentToken.getState()
							.getProcessDefinition().findStateDefinition(
									"staffEnterEnd");
					parentToken.setState(null);
					parentToken.setState(endState);
					BpmContextHolder.getContext().getProcessManagementService()
							.update(parentToken);
				}
			}
		}
	}
}
